console.log("访客阁页面脚本已加载");

document.addEventListener('DOMContentLoaded', () => {
    // 初始加载留言
    renderLanternWall();

    const guestbookForm = document.getElementById('guestbook-form');
    if (guestbookForm) {
        guestbookForm.addEventListener('submit', (event) => {
            event.preventDefault(); // Prevent default form submission

            const nickname = event.target.nickname.value.trim();
            const message = event.target.message.value.trim();

            if (!nickname || !message) {
                alert("昵称和留言不能为空！");
                return;
            }

            // 将新留言添加到模拟数据中
            guestbookData.push({ nickname, message });

            // 重新渲染留言墙
            renderLanternWall();
            
            // 清空表单
            event.target.reset();
        });
    }

    // 页面切换淡入动效（访客阁主内容区）
    const main = document.querySelector('main');
    if(main) main.classList.add('fade-page-enter');
});

function renderLanternWall() {
    const container = document.querySelector('.lantern-container');
    if (!container) return;

    container.innerHTML = ''; // 清空现有内容

    guestbookData.forEach(entry => {
        const lantern = document.createElement('div');
        lantern.className = 'lantern';

        const content = `
            <div class="lantern-content">
                <p class="message-text">${escapeHTML(entry.message)}</p>
                <p class="nickname-text">- ${escapeHTML(entry.nickname)}</p>
            </div>
        `;
        lantern.innerHTML = content;
        container.appendChild(lantern);
    });
}

function escapeHTML(str) {
    const p = document.createElement('p');
    p.appendChild(document.createTextNode(str));
    return p.innerHTML;
}

// 灯笼漂浮发光动效（访客阁专用）
(function() {
  const canvas = document.getElementById('lantern-bg-canvas');
  if (!canvas) return;
  const ctx = canvas.getContext('2d');
  let width = window.innerWidth;
  let height = window.innerHeight;
  function resize() {
    width = window.innerWidth;
    height = window.innerHeight;
    canvas.width = width;
    canvas.height = height;
  }
  resize();
  window.addEventListener('resize', resize);
  // 灯笼参数
  const lanterns = Array.from({length: 8}, (_,i) => ({
    x: Math.random()*width,
    y: height*Math.random()*0.7+height*0.1,
    r: 32+Math.random()*18,
    dx: -0.08+Math.random()*0.16,
    dy: -0.04+Math.random()*0.08,
    alpha: 0.7+Math.random()*0.18,
    t: Math.random()*Math.PI*2
  }));
  const lanternImg = new window.Image();
  lanternImg.src = 'assets/images/bg-lantern.png';
  function draw() {
    ctx.clearRect(0,0,width,height);
    const isNight = document.body.classList.contains('night-mode');
    lanterns.forEach(l => {
      ctx.save();
      ctx.globalAlpha = l.alpha * (isNight?1.2:1);
      // 灯笼发光
      ctx.beginPath();
      ctx.arc(l.x, l.y+l.r*0.3, l.r*0.7, 0, Math.PI*2);
      ctx.closePath();
      ctx.fillStyle = isNight ? 'rgba(194,59,35,0.18)' : 'rgba(255,220,120,0.18)';
      ctx.shadowColor = isNight ? '#c23b23' : '#ffd878';
      ctx.shadowBlur = 32;
      ctx.fill();
      ctx.shadowBlur = 0;
      // 灯笼主体
      if (lanternImg.complete && lanternImg.naturalWidth) {
        ctx.drawImage(lanternImg, l.x-l.r, l.y-l.r, l.r*2, l.r*2);
      } else {
        ctx.beginPath();
        ctx.ellipse(l.x, l.y, l.r*0.8, l.r, 0, 0, Math.PI*2);
        ctx.fillStyle = isNight ? '#c23b23' : '#ffd878';
        ctx.fill();
      }
      ctx.restore();
    });
  }
  function animate() {
    lanterns.forEach(l => {
      l.x += l.dx + Math.sin(l.t)*0.12;
      l.y += l.dy + Math.cos(l.t)*0.08;
      l.t += 0.006+Math.random()*0.003;
      if (l.x < -l.r) l.x = width+l.r;
      if (l.x > width+l.r) l.x = -l.r;
      if (l.y < -l.r) l.y = height+l.r;
      if (l.y > height+l.r) l.y = -l.r;
    });
    draw();
    requestAnimationFrame(animate);
  }
  animate();
  // 夜间模式切换时重绘
  const obs = new MutationObserver(draw);
  obs.observe(document.body, {attributes:true, attributeFilter:['class']});
})();

// 飞鸽传书icon点击信封滑动动画
(function() {
  const btn = document.getElementById('sendPigeonBtn');
  const anim = document.getElementById('envelopeAnim');
  if (!btn || !anim) return;
  btn.addEventListener('click', function() {
    anim.innerHTML = `<svg class='envelope-anim' width='38' height='28' viewBox='0 0 38 28' fill='none' xmlns='http://www.w3.org/2000/svg'>
      <rect x='2' y='6' width='34' height='18' rx='4' fill='#fffbe6' stroke='#b0a084' stroke-width='2'/>
      <path d='M2 6l17 13 17-13' stroke='#c23b23' stroke-width='2' fill='none'/>
      <rect x='10' y='2' width='18' height='8' rx='2' fill='#fffbe6' stroke='#b0a084' stroke-width='1.5'/>
    </svg>`;
    setTimeout(()=>{anim.innerHTML='';}, 1200);
  });
})();

function renderGuestbook() {
  const list = document.getElementById('guestbook-list');
  if (!list) return;
  list.innerHTML = '';
  guestbookData.forEach((item, idx) => {
    const div = document.createElement('div');
    div.className = 'guestbook-item';
    div.innerHTML = `
      <div class='guestbook-nickname'>${item.nickname}</div>
      <div class='guestbook-message'>${item.message}</div>
    `;
    // 新留言弹入动画
    if(idx === guestbookData.length-1) {
      div.style.opacity = 0;
      setTimeout(()=>{div.style.transition='opacity 0.7s';div.style.opacity=1;}, 80);
    }
    list.appendChild(div);
  });
}

// 访客阁文化彩蛋气泡
(function() {
  const mainTitle = document.querySelector('.section-title');
  if (!mainTitle) return;
  let bubble;
  function showEgg() {
    if (bubble) return;
    bubble = document.createElement('div');
    bubble.className = 'cultural-egg-bubble';
    bubble.innerHTML = '文物小知识：灯笼，象征团圆与美好祝愿，常用于节庆与祈福。';
    mainTitle.parentElement.appendChild(bubble);
    setTimeout(()=>{bubble.style.opacity=1; bubble.style.pointerEvents='auto';}, 80);
    setTimeout(hideEgg, 4200);
  }
  function hideEgg() {
    if (bubble) {
      bubble.style.opacity = 0;
      setTimeout(()=>{if(bubble) {bubble.remove(); bubble=null;}}, 400);
    }
  }
  mainTitle.addEventListener('mouseenter', showEgg);
  mainTitle.addEventListener('mouseleave', hideEgg);
  setTimeout(showEgg, 1200);
})(); 